﻿/*----------------------------------------------------------
 *  创建者：wangjj
 *  创建时间：2020-3-30 10:01:35
 *  功能描述：定时器模块-Windown扩展助手
 *  
 *  更新历史：
 ----------------------------------------------------------*/
using Microsoft.VisualBasic;
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;

namespace minidwm
{
    /// <summary>
    /// Windown扩展助手
    /// </summary>
    public partial class Formshutdown : Form
    {
        /// <summary>
        /// 初始化
        /// </summary>
        public Formshutdown()
        {
            InitializeComponent();
        }

        #region 定义
        string strHour = DateTime.Now.TimeOfDay.Hours.ToString();
        string strMouit = DateTime.Now.TimeOfDay.Minutes.ToString();
        string strSecon = DateTime.Now.TimeOfDay.Seconds.ToString();
        private const int SE_PRIVILEGE_ENABLED = 0x00000002;
        private const int TOKEN_QUERY = 0x00000008;
        private const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
        private const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege";
        /// <summary>
        /// 注销代码
        /// </summary>
        private const int EWX_LOGOFF = 0x00000000;
        /// <summary>
        /// 关机
        /// </summary>
        private const int EWX_SHUTDOWN = 0x00000001;
        /// <summary>
        /// 重启
        /// </summary>
        private const int EWX_REBOOT = 0x00000002;
        private const int EWX_FORCE = 0x00000004;
        #endregion

        #region 公共方法
        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        public struct TokPriv1Luid
        {
            public int Count;
            public long Luid;
            public int Attr;
        }
        [DllImport("kernel32", EntryPoint = "Beep")]
        public extern static int Beep(int dwfreq, int dwduration);
        public int intHour, intMouit, intSecon;
        [DllImport("kernel32.dll", ExactSpelling = true)]
        // GetCurrentProcess函数返回当前进程的一个句柄
        public static extern IntPtr GetCurrentProcess();

        [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
        // OpenProcessToken函数打开一个进程的访问代号
        public static extern bool OpenProcessToken(IntPtr ProcessHandles, int DesiredAccess, ref IntPtr TokenHandle);

        [DllImport("advapi32.dll", SetLastError = true)]
        // LookupPrivilegeValue函数获得本地唯一的标示符(LUID)，用于在特定的系统中 
        // 表示特定的优先权。 
        public static extern bool LookupPrivilegeValue(string lpSystemName, string lpName, ref long lpLuid);

        // AdjustTokenPrivileges函数允许或者禁用指定访问记号的优先权。 
        // 允许或者禁用优先权需要TOKEN_ADJUST_PRIVILEGES访问权限。 
        [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
        public static extern bool AdjustTokenPrivileges(IntPtr TokenHandle, bool DisableAllPrivileges, ref TokPriv1Luid NewState, int BufferLength, IntPtr PreviousState, IntPtr ReturnLength);

        // ExitWindowsEx函数可以注销，关机或者重新启动系统
        [DllImport("user32.dll", ExactSpelling = true, SetLastError = true)]
        public static extern bool ExitWindowsEx(int flg, int rea);
        [DllImport("user32.dll")]
        private static extern void LockWorkStation();//锁定系统

        //开启显示器
        public static void TurnOn()
        {
            SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, -1);
        }
        //关闭显示器
        public static void TurnOff()
        {
            SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, 2);
        }

        /// <summary>
        /// 发送信息
        /// </summary>
        /// <param name="hWnd"></param>
        /// <param name="Msg"></param>
        /// <param name="wParam"></param>
        /// <param name="lParam"></param>
        /// <returns></returns>
        [DllImport("user32.dll")]
        public static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);

        private static readonly IntPtr HWND_BROADCAST = new IntPtr(0xffff);
        private const uint WM_SYSCOMMAND = 0x0112;
        private const int SC_MONITORPOWER = 0xf170;
        #endregion
        private static void RebootCommand(int flg)
        {
            bool ok;
            TokPriv1Luid tp;
            IntPtr hproc = GetCurrentProcess(); // 得到当前的进程
            IntPtr htok = IntPtr.Zero;
            ok = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
            tp.Count = 1;
            tp.Luid = 0;
            tp.Attr = SE_PRIVILEGE_ENABLED;
            ok = LookupPrivilegeValue(null, SE_SHUTDOWN_NAME, ref tp.Luid);
            ok = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
            ok = ExitWindowsEx(flg, 0);
        }


        private void timer1_Tick(object sender, EventArgs e)
        {
            tbdatetime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }

        private void Formshutdown_Load(object sender, EventArgs e)
        {
            numericUpDownhours.Value = Int32.Parse(strHour);
            numericUpDownminutes.Value = Int32.Parse(strMouit);
            numericUpDownseconds.Value = Int32.Parse(strSecon);

        }
        //设置小时
        private void numericUpDownhours_ValueChanged(object sender, EventArgs e)
        {
            string Hour, Minute, second;
            if (numericUpDownhours.Value == 24)
            {
                numericUpDownhours.Value = 0;
                intHour = Convert.ToInt32(numericUpDownhours.Value);
                if (Convert.ToInt32(intHour) < 10)
                {
                    Hour = "0" + intHour.ToString() + ":";
                }
                else
                {
                    Hour = intHour.ToString() + ":";
                }
                if (Convert.ToInt32(intMouit) < 10)
                {
                    Minute = "0" + intMouit.ToString() + ":";
                }
                else
                {
                    Minute = intMouit.ToString() + ":";
                }
                if (Convert.ToInt32(intSecon) < 10)
                {
                    second = "0" + intSecon.ToString();
                }
                else
                {
                    second = intSecon.ToString();
                }
                tbtime.Text = Hour + Minute + second;
            }
            else
            {
                intHour = Convert.ToInt32(numericUpDownhours.Value);
                if (Convert.ToInt32(intHour) < 10)
                {
                    Hour = "0" + intHour.ToString() + ":";
                }
                else
                {
                    Hour = intHour.ToString() + ":";
                }
                if (Convert.ToInt32(intMouit) < 10)
                {
                    Minute = "0" + intMouit.ToString() + ":";
                }
                else
                {
                    Minute = intMouit.ToString() + ":";
                }
                if (Convert.ToInt32(intSecon) < 10)
                {
                    second = "0" + intSecon.ToString();
                }
                else
                {
                    second = intSecon.ToString();
                }
                tbtime.Text = Hour + Minute + second;

            }
        }
        //设置分
        private void numericUpDownminutes_ValueChanged(object sender, EventArgs e)
        {
            string Hour, Minute, second;
            if (numericUpDownminutes.Value == 60)
            {
                numericUpDownminutes.Value = 0;
                numericUpDownhours.Value = Convert.ToInt32(numericUpDownhours.Value) + 1;
                intMouit = Convert.ToInt32(numericUpDownminutes.Value);
                intHour = Convert.ToInt32(numericUpDownhours.Value);
                if (Convert.ToInt32(intHour) < 10)
                {
                    Hour = "0" + intHour.ToString() + ":";
                }
                else
                {
                    Hour = intHour.ToString() + ":";
                }
                if (Convert.ToInt32(intMouit) < 10)
                {
                    Minute = "0" + intMouit.ToString() + ":";
                }
                else
                {
                    Minute = intMouit.ToString() + ":";
                }
                if (Convert.ToInt32(intSecon) < 10)
                {
                    second = "0" + intSecon.ToString();
                }
                else
                {
                    second = intSecon.ToString();
                }
                tbtime.Text = Hour + Minute + second;

            }
            else
            {
                intMouit = Convert.ToInt32(numericUpDownminutes.Value);
                if (Convert.ToInt32(intHour) < 10)
                {
                    Hour = "0" + intHour.ToString() + ":";
                }
                else
                {
                    Hour = intHour.ToString() + ":";
                }
                if (Convert.ToInt32(intMouit) < 10)
                {
                    Minute = "0" + intMouit.ToString() + ":";
                }
                else
                {
                    Minute = intMouit.ToString() + ":";
                }
                if (Convert.ToInt32(intSecon) < 10)
                {
                    second = "0" + intSecon.ToString();
                }
                else
                {
                    second = intSecon.ToString();
                }
                tbtime.Text = Hour + Minute + second;

            }
        }
        //设置秒
        private void numericUpDownseconds_ValueChanged(object sender, EventArgs e)
        {
            string Hour, Minute, second;
            if (numericUpDownseconds.Value == 60)
            {
                numericUpDownseconds.Value = 0;
                numericUpDownminutes.Value = Convert.ToInt32(numericUpDownminutes.Value) + 1;
                intMouit = Convert.ToInt32(numericUpDownminutes.Value);
                intSecon = Convert.ToInt32(numericUpDownseconds.Value);
                if (Convert.ToInt32(intHour) < 10)
                {
                    Hour = "0" + intHour.ToString() + ":";
                }
                else
                {
                    Hour = intHour.ToString() + ":";
                }
                if (Convert.ToInt32(intMouit) < 10)
                {
                    Minute = "0" + intMouit.ToString() + ":";
                }
                else
                {
                    Minute = intMouit.ToString() + ":";
                }
                if (Convert.ToInt32(intSecon) < 10)
                {
                    second = "0" + intSecon.ToString();
                }
                else
                {
                    second = intSecon.ToString();
                }
                tbtime.Text = Hour + Minute + second;
            }
            else
            {

                intSecon = Convert.ToInt32(numericUpDownseconds.Value);
                if (Convert.ToInt32(intHour) < 10)
                {
                    Hour = "0" + intHour.ToString() + ":";
                }
                else
                {
                    Hour = intHour.ToString() + ":";
                }
                if (Convert.ToInt32(intMouit) < 10)
                {
                    Minute = "0" + intMouit.ToString() + ":";
                }
                else
                {
                    Minute = intMouit.ToString() + ":";
                }
                if (Convert.ToInt32(intSecon) < 10)
                {
                    second = "0" + intSecon.ToString();
                }
                else
                {
                    second = intSecon.ToString();
                }
                tbtime.Text = Hour + Minute + second;


            }
        }

        /// <summary>
        /// 设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnok_Click(object sender, EventArgs e)
        {

            DateTime get_time1 = Convert.ToDateTime(DateTime.Now.ToString());
            DateTime sta_ontime1 = Convert.ToDateTime(Convert.ToDateTime(tbtime.Text.Trim().ToString()));
            //计算多少秒
            long dat = DateAndTime.DateDiff("s", get_time1, sta_ontime1, FirstDayOfWeek.Sunday, FirstWeekOfYear.FirstFourDays);
            if (dat > 0)
            {
                if (timer2.Enabled != true)
                {
                    timer2.Enabled = true;
                }
                else
                {
                    MessageBox.Show("时钟已经启动，请取消后，再启动");
                }
            }
            else
            {
                timer2.Enabled = false;
                lbtime.Text = "";
                MessageBox.Show("您输入的时间数超过24小时！请重新输入");
            }
            if (tbcontent.TextLength <= 0 && cbprompt.Checked == true)
            {
                MessageBox.Show("请输入提示内容！");
            }
        }

        /// <summary>
        /// 定时器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer2_Tick(object sender, EventArgs e)
        {
            DateTime get_time1 = Convert.ToDateTime(DateTime.Now.ToString());
            DateTime sta_ontime1 = Convert.ToDateTime(Convert.ToDateTime(tbtime.Text.Trim().ToString()));
            long dat = DateAndTime.DateDiff("s", get_time1, sta_ontime1, FirstDayOfWeek.Sunday, FirstWeekOfYear.FirstFourDays);
            if (dat == 0)
            {
                Beep(200, 500);
                timer2.Enabled = false;
                //if (cbLock.Checked == true || cbLogoff.Checked == true || cbrestart.Checked == true || cbshutdown.Checked == true || cbsleep.Checked == true && cbprompt.Checked == true)
                //{
                //    DialogResult getok = MessageBox.Show(tbcontent.Text.ToString(), "提示", MessageBoxButtons.OKCancel);
                //    //判断是否是点击ok
                //    if (getok == DialogResult.OK)
                //    {
                //        if (cbLock.Checked == true)
                //        {
                //            LockWorkStation();
                //        }

                //        else if (cbLogoff.Checked == true)
                //        {
                //            RebootCommand(EWX_LOGOFF + EWX_FORCE);
                //        }

                //        else if (cbrestart.Checked == true)
                //        {
                //            RebootCommand(EWX_REBOOT + EWX_FORCE);
                //        }

                //        else if (cbshutdown.Checked == true)
                //        {
                //            RebootCommand(EWX_SHUTDOWN + EWX_FORCE);
                //        }

                //        else if (cbsleep.Checked == true)
                //        {
                //            TurnOff();
                //            timer2.Enabled = false;
                //        }
                //    }
                //}
                //else
                //{
                if (cbLock.Checked == true)
                {
                    LockWorkStation();
                }

                else if (cbLogoff.Checked == true)
                {
                    RebootCommand(EWX_LOGOFF + EWX_FORCE);
                }

                else if (cbrestart.Checked == true)
                {
                    RebootCommand(EWX_REBOOT + EWX_FORCE);
                }

                else if (cbshutdown.Checked == true)
                {
                    RebootCommand(EWX_SHUTDOWN + EWX_FORCE);
                }

                else if (cbsleep.Checked == true)
                {
                    TurnOff();
                    timer2.Enabled = false;
                }
                else
                {
                    this.noIcon.Visible = true; // 设置提示控件可见
                                                // 显示气泡提示，时间为1秒，内容为当前时间，图标为消息图标
                    this.noIcon.ShowBalloonTip(1000, "友情提示：", tbcontent.Text.ToString(), ToolTipIcon.Info);
                }

                // }
                lbtime.Text = "";
            }
            else
            {
                if (cbLock.Checked == true)
                {
                    lbtime.Text = "倒计时" + dat.ToString() + "秒后" + cbLock.Text;
                }

                else if (cbLogoff.Checked == true)
                {
                    lbtime.Text = "倒计时" + dat.ToString() + "秒后" + cbLogoff.Text;
                }

                else if (cbrestart.Checked == true)
                {
                    lbtime.Text = "倒计时" + dat.ToString() + "秒后" + cbrestart.Text;
                }

                else if (cbshutdown.Checked == true)
                {
                    lbtime.Text = "倒计时" + dat.ToString() + "秒后" + cbshutdown.Text;
                }

                else if (cbsleep.Checked == true)
                {
                    lbtime.Text = "倒计时" + dat.ToString() + "秒后" + cbsleep.Text;
                }
                else
                {
                    lbtime.Text = "倒计时" + dat.ToString() + "秒";
                }
            }
        }

        private void cbrestart_CheckedChanged(object sender, EventArgs e)
        {
            if (cbrestart.Checked == true)
            {
                cbLock.Enabled = false;
                cbLogoff.Enabled = false;
                cbshutdown.Enabled = false;
                cbsleep.Enabled = false;
            }
            else
            {
                cbLock.Enabled = true;
                cbLogoff.Enabled = true;
                cbprompt.Enabled = true;
                cbshutdown.Enabled = true;
                cbsleep.Enabled = true;
            }
        }

        private void cbsleep_CheckedChanged(object sender, EventArgs e)
        {
            if (cbsleep.Checked == true)
            {
                cbLock.Enabled = false;
                cbLogoff.Enabled = false;
                cbshutdown.Enabled = false;
                cbrestart.Enabled = false;
            }
            else
            {
                cbLock.Enabled = true;
                cbLogoff.Enabled = true;
                cbprompt.Enabled = true;
                cbshutdown.Enabled = true;
                cbrestart.Enabled = true;
            }
        }

        private void cbLogoff_CheckedChanged(object sender, EventArgs e)
        {
            if (cbLogoff.Checked == true)
            {
                cbLock.Enabled = false;
                cbsleep.Enabled = false;
                cbshutdown.Enabled = false;
                cbrestart.Enabled = false;
            }
            else
            {
                cbLock.Enabled = true;
                cbsleep.Enabled = true;
                cbprompt.Enabled = true;
                cbshutdown.Enabled = true;
                cbrestart.Enabled = true;
            }
        }

        private void cbshutdown_CheckedChanged(object sender, EventArgs e)
        {
            if (cbshutdown.Checked == true)
            {
                cbLock.Enabled = false;
                cbsleep.Enabled = false;
                cbLogoff.Enabled = false;
                cbrestart.Enabled = false;
            }
            else
            {
                cbLock.Enabled = true;
                cbsleep.Enabled = true;
                cbprompt.Enabled = true;
                cbLogoff.Enabled = true;
                cbrestart.Enabled = true;
            }
        }

        private void cbprompt_CheckedChanged(object sender, EventArgs e)
        {
            if (cbprompt.Checked == true)
            {
                tbcontent.Enabled = true;

            }
            else
            {
                tbcontent.Enabled = false;
            }
        }

        private void cbLock_CheckedChanged(object sender, EventArgs e)
        {
            if (cbLock.Checked == true)
            {
                cbshutdown.Enabled = false;
                cbsleep.Enabled = false;
                cbLogoff.Enabled = false;
                cbrestart.Enabled = false;
            }
            else
            {
                cbshutdown.Enabled = true;
                cbsleep.Enabled = true;
                cbprompt.Enabled = true;
                cbLogoff.Enabled = true;
                cbrestart.Enabled = true;
            }
        }

        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btncancel_Click(object sender, EventArgs e)
        {
            this.Tiptimer.Enabled = true;
        }
        /// <summary>
        /// 查看基金页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Increase_Click(object sender, EventArgs e)
        {
            this.Hide();
            this.Dispose();
            StockFrom increase = new StockFrom();
            increase.Show();
        }

        /// <summary>
        /// 关闭程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Formshutdown_FormClosed(object sender, FormClosedEventArgs e)
        {
            DialogResult dr = MessageBox.Show("确定要关闭本程序？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (dr == DialogResult.Yes)
            {
                this.Close();
                this.Dispose();
            }
        }

        /// <summary>
        /// 系统时间定时器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Tiptimer_Tick(object sender, EventArgs e)
        {
            this.noIcon.Visible = true; // 设置提示控件可见
            // 显示气泡提示，时间为1秒，内容为当前时间，图标为消息图标
            this.noIcon.ShowBalloonTip(10000, "当前时间：", DateTime.Now.ToString(), ToolTipIcon.Info);
            Thread.Sleep(1000);
            this.timer1.Enabled = false;
            timer2.Enabled = false;
            lbtime.Text = "";
            this.Tiptimer.Enabled = false;
        }
    }
}
